package com.egreen.admin.aspect;

import com.egreen.admin.common.JwtExceptions;
import com.egreen.admin.common.exception.JwtFormatException;
import com.egreen.admin.dao.OperationRecordDao;
import com.egreen.admin.utils.JwtUtil;
import com.egreen.admin.utils.AdminOperationRecord;
import com.egreen.common.pojo.entity.admin.OperationRecord;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Aspect
@Component
public class AdminAspect {
    @Autowired
    OperationRecordDao operationRecordDao;
    @Autowired
    JwtUtil jwtUtil;

    //切点
    @Pointcut("@annotation(com.egreen.admin.utils.AdminOperationRecord)")
    public void test() {
    }

    /**
     * 前置执行刷新配置
     *
     * @param
     * @return
     */
    //通知类
    @AfterReturning("test() &&@annotation(admincheck)")
    public void LoadingConfig(AdminOperationRecord admincheck) {
        //获取请求
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        String token = request.getHeader("Token");
        Integer adminId = getAdminId(token);
        OperationRecord operationRecord = new OperationRecord();
        operationRecord.setAdminId(adminId);
        operationRecord.setOperationDiscribe(admincheck.message());
        operationRecord.setOperationType(admincheck.type());
        LocalDateTime time = LocalDateTime.now();
        operationRecord.setOperationTime(time);
        int insert = operationRecordDao.insert(operationRecord);
        if (insert != 1) {
            throw new IllegalArgumentException();
        }
    }

    /**
     * 根据token获取管理员id
     *
     * @param token
     * @return
     */
    public Integer getAdminId(String token) {
        try {
            jwtUtil.checkAdminJwt(token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new JwtFormatException();
        }
        Claims clamis = (Claims) jwtUtil.checkAdminJwt(token);
        return (Integer) clamis.get("adminId");
    }

}
